import {
  getOrderStatusList,
  updateOrderStatus,
  downloadExcel,
  createOrder
} from "@/api/dashboard";
import { PaginationProps } from "@pureadmin/table";
import { reactive, ref, h } from "vue";
import { message } from "@/utils/message";
import type { PlusColumn } from "plus-pro-components";
import type { FormItemProps } from "./types";
/** 跳转详情依赖 */
import { isString, isEmpty } from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { router } from "@/router";

import { addDialog } from "@/components/ReDialog";
import { type LocationQueryRaw, type RouteParamsRaw } from "vue-router";
import dayjs from "dayjs";
import CreateForm from "../form/add.vue";
import UploadForm from "../form/upload.vue";

// 跳转订单详情
/** 跳转详情页方法 */
export function useDetail() {
  function toDetail(
    parameter: LocationQueryRaw | RouteParamsRaw,
    model: "query" | "params"
  ) {
    Object.keys(parameter).forEach(param => {
      if (!isString(parameter[param])) {
        parameter[param] = parameter[param].toString();
      }
    });
    if (model === "query") {
      // 保存信息到标签页
      useMultiTagsStoreHook().handleTags("push", {
        path: `/tabs/query-detail`,
        name: "TabQueryDetail",
        query: parameter,
        meta: {
          title: {
            zh: `No.${parameter.id} - 详情信息`,
            en: `No.${parameter.id} - DetailInfo`
          },
          // 如果使用的是非国际化精简版title可以像下面这么写
          // title: `No.${index} - 详情信息`,
          // 最大打开标签数
          dynamicLevel: 3
        }
      });
      // 路由跳转
      router.push({ name: "TabQueryDetail", query: parameter });
    } else if (model === "params") {
      useMultiTagsStoreHook().handleTags("push", {
        path: `/dashboard/order/:id`,
        name: "OrderDetail",
        params: parameter,
        meta: {
          title: `订单 ${parameter.id}`
          // title: {
          //   zh: `No.${parameter.id} - 详情信息`,
          //   en: `No.${parameter.id} - DetailInfo`
          // }
          // 如果使用的是非国际化精简版title可以像下面这么写
          // title: `No.${index} - 详情信息`,
        }
      });
      router.push({ name: "OrderDetail", params: parameter });
    }
  }

  return { toDetail, router };
}

// 搜索表单配置
const searchColumns: PlusColumn[] = [
  {
    label: "商品名称",
    prop: "goodsName",
    valueType: "input",
    fieldProps: {
      placeholder: "请输入商品名称",
      size: "small"
    }
  },
  {
    label: "商品货号",
    prop: "goodsCode",
    valueType: "input",
    fieldProps: {
      placeholder: "请输入商品货号",
      size: "small"
    }
  },
  {
    label: "订单号",
    prop: "orderNo",
    valueType: "input",
    fieldProps: {
      placeholder: "请输入订单号",
      size: "small"
    }
  },
  {
    label: "采购单位",
    prop: "purchasingUnit",
    valueType: "input",
    fieldProps: {
      placeholder: "请输入采购单位",
      size: "small"
    }
  },
  {
    label: "采购部门",
    prop: "purchasingDept",
    valueType: "input",
    fieldProps: {
      placeholder: "请输入采购部门",
      size: "small"
    }
  },
  {
    label: "采购人",
    prop: "purchaser",
    valueType: "input",
    fieldProps: {
      placeholder: "请输入采购人",
      size: "small"
    }
  },
  {
    label: "收货人",
    prop: "receiver",
    valueType: "input",
    fieldProps: {
      placeholder: "请输入收货人",
      size: "small"
    }
  },
  {
    label: "品牌",
    prop: "brand",
    valueType: "input",
    fieldProps: {
      placeholder: "请输入品牌名称",
      size: "small"
    }
  },
  {
    label: "商品分类",
    prop: "goodsCategory",
    valueType: "select",
    fieldProps: {
      placeholder: "请选择商品分类",
      size: "small",
      style: {
        width: "100px"
      }
    },
    options: [
      {
        label: "全部分类",
        value: ""
      },
      {
        label: "电子产品",
        value: "electronics"
      },
      {
        label: "办公用品",
        value: "office"
      },
      {
        label: "生活用品",
        value: "daily"
      },
      {
        label: "工业用品",
        value: "industrial"
      }
    ]
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    fieldProps: {
      placeholder: "请选择状态",
      size: "small",
      style: {
        width: "100px"
      }
    },
    options: [
      {
        label: "全部",
        value: 0
      },
      {
        label: "待处理",
        value: 1,
        color: "orange"
      },
      {
        label: "已发货",
        value: 2,
        color: "blue"
      },
      {
        label: "待回款",
        value: 3,
        color: "yellow"
      },
      {
        label: "已回款",
        value: 4,
        color: "green"
      },
      {
        label: "售后中",
        value: 6,
        color: "red"
      }
    ]
  },
  {
    label: "规格编码",
    prop: "specCode",
    valueType: "input",
    fieldProps: {
      placeholder: "请输入规格编码",
      size: "small"
    }
  },
  {
    label: "时间范围",
    prop: "timeRange",
    valueType: "date-picker",
    colProps: {
      span: 8
    },
    fieldProps: {
      type: "daterange",
      startPlaceholder: "开始时间",
      endPlaceholder: "结束时间",
      // format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "x",
      size: "small",
      style: {
        width: "200px"
      }
    }
  }
];

// 搜索表单的初始化状态
const searchState = ref({
  goodsName: "", // 商品名称
  goodsCode: "", // 商品货号
  orderNo: "", // 订单号
  purchasingUnit: "", // 采购单位
  purchasingDept: "", // 采购部门
  purchaser: "", // 采购人
  receiver: "", // 收货人
  status: 0, // 状态
  timeRange: [
    // 时间范围 - 默认近一周
    dayjs().subtract(7, "day").valueOf(),
    dayjs().valueOf()
  ],
  goodsCategory: "", // 商品分类
  brand: "", // 品牌
  specCode: "", // 规格编码
  tags: [] // 标签（多选）
});

// 搜索方法
const handlerSearch = values => {
  // 处理搜索逻辑
  console.log(values, "search");
  filterStatus.value = String(values.status);
  getStatusList();
};

// 订单基础信息
const columns: TableColumnList = [
  {
    type: "expand",
    slot: "expand"
  },
  {
    label: "订单号",
    // prop: "orderno",
    width: 200,
    cellRenderer: ({ row }) => {
      return (
        <div
          class="text-primary cursor-pointer"
          onClick={() => useDetail().toDetail({ id: row.orderno }, "params")}
        >
          {row.orderno}
        </div>
      );
    }
  },
  {
    label: "订单时间",
    prop: "orderdate",
    width: 140
  },
  {
    label: "采购单位",
    prop: "purchasingunit"
  },
  {
    label: "采购人",
    prop: "contactsname",
    width: 120
  },
  {
    label: "订单金额",
    prop: "price",
    width: 120
  },
  {
    label: "销售员",
    prop: "salesman",
    width: 120,
    cellRenderer: ({ row }) => {
      return (
        <el-select
          width="120"
          v-model={row.salesman}
          onChange={() => changeSalesman(row)}
          size="small"
        >
          <el-option label="未填写" value="未填写"></el-option>
          <el-option label="杨佩颖" value="杨佩颖"></el-option>
          <el-option label="周凯歌" value="周凯歌"></el-option>
          <el-option label="温博森" value="温博森"></el-option>
          <el-option label="李优美" value="李优美"></el-option>
        </el-select>
      );
    }
  },
  {
    label: "订单状态",
    prop: "status",
    width: 120,
    cellRenderer: ({ row }) => {
      return (
        <el-select
          width="120"
          v-model={row.status}
          onChange={() => changeOrderStatus(row)}
          size="small"
        >
          <el-option label="待处理" value="待处理"></el-option>
          <el-option label="已发货" value="已发货"></el-option>
          <el-option label="待回款" value="待回款"></el-option>
          <el-option label="已回款" value="已回款"></el-option>
        </el-select>
      );
    }
  },
  {
    label: "操作",
    slot: "operation"
  }
];

const childColumns: TableColumnList = [
  {
    label: "商品编号",
    prop: "fgoodcode"
  },
  {
    label: "商品名称",
    prop: "fgoodname"
  },
  {
    label: "品牌",
    prop: "fbrand"
  },
  {
    label: "规格",
    prop: "fspec"
  },
  {
    label: "单价",
    prop: "fprice"
  },
  {
    label: "数量",
    prop: "fquantity"
  },
  {
    label: "总价",
    prop: "fbidprice"
  },
  {
    label: "单位",
    prop: "funit"
  }
];

const productList = ref([] as any[]);

// 统一查询方法
const getStatusList = async () => {
  // 判断时间是否为空
  let startTime = 0,
    endTime = 0;
  if (searchState.value.timeRange == null) {
    startTime = 0;
    endTime = 0;
  } else {
    startTime = Math.floor(searchState.value.timeRange[0] / 1000);
    endTime = Math.floor(searchState.value.timeRange[1] / 1000);
  }

  const res = await getOrderStatusList({
    typeid: searchState.value.status,
    orderno: searchState.value.orderNo,
    purchasingunit: searchState.value.purchasingUnit,
    contactsname: searchState.value.purchaser,
    starttime: startTime,
    endtime: endTime,
    size: pagination.pageSize,
    page: pagination.currentPage
  });
  productList.value = res.data.orderlist || [];
  pagination.total = res.data.total || 0;
};

/** 销售员改变时，更新searchData中的销售员 */
const changeSalesman = async row => {
  const res = await updateOrderStatus({
    orderno: row.orderno,
    status: row.status,
    note: row.note || "",
    salesman: row.salesman || ""
  });
  console.log(res);
  getStatusList();
};

/** 顶部订单筛选部分 */
const filterStatus = ref("0");
/** 订单状态筛选 */
const statusFilterList = [
  {
    label: "全部订单",
    value: "0"
  },
  {
    label: "待处理",
    value: "1"
  },
  {
    label: "已发货",
    value: "2"
  },
  {
    label: "待回款",
    value: "3"
  },
  {
    label: "已回款",
    value: "4"
  },
  {
    label: "售后中",
    value: "6"
  }
];
/** 订单状态筛选 */
const handleSelect = (key: string) => {
  filterStatus.value = key;
  searchState.value.status = parseInt(key);
  getStatusList();
};

/** 翻页器定义 */
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});

/** 翻页器-改变页数 */
function handlePageChange(val) {
  pagination.currentPage = val;
  getStatusList();
}

function handleSizeChange(val) {
  pagination.pageSize = val;
  getStatusList();
}

const changeOrderStatus = async row => {
  console.log("订单状态发生改变");
  console.log(row);
  const res = await updateOrderStatus({
    orderno: row.orderno,
    status: row.status,
    note: row.note || "",
    salesman: row.salesman || ""
  });
  getStatusList();
};

// 取消订单
const changeOrderStatusClose = async row => {
  const res = await updateOrderStatus({
    orderno: row.orderno,
    status: "取消订单",
    note: row.note || "",
    salesman: row.salesman || ""
  });
  getStatusList();
};

// 售后订单
const changeOrderStatusProblem = async row => {
  const res = await updateOrderStatus({
    orderno: row.orderno,
    status: "售后中",
    note: row.note || "",
    salesman: row.salesman || ""
  });
  getStatusList();
};

// 添加展开行的key数组
const expandedRowKeys = ref<string[]>([]);

// 展开行按钮事件
const handleExpandChange = (row, expandedRows) => {
  expandedRowKeys.value = expandedRows.map(item => item.orderno);
};

// 表格行点击事件
const handleRowClick = row => {
  const index = expandedRowKeys.value.indexOf(row.orderno);
  if (index === -1) {
    expandedRowKeys.value.push(row.orderno);
  } else {
    expandedRowKeys.value.splice(index, 1);
  }
};

/**
 * 对话框管理 hook
 */
export function useDialog() {
  const formRef = ref();
  const uploadRef = ref();

  /**
   * 使用 addOrderDialog 新增订单弹窗
   * @param title 操作类型：新增或修改
   * @param row 初始数据（修改时使用）
   */
  const addOrderDialog = () => {
    // 初始化表单数据（仅保留新增）
    const formInline: FormItemProps = {
      orderNo: "",
      purchasingUnit: "",
      purchasingDept: "",
      purchaser: "",
      purchaserPhone: "",
      receiver: "",
      receiverPhone: "",
      receiverAddress: "",
      orderTime: "",
      productList: [
        {
          /** 商品编号 */
          goodCode: "",
          /** 商品名称 */
          goodName: "",
          /** 品牌 */
          brand: "",
          /** 规格 */
          spec: "",
          /** 单价 */
          price: null,
          /** 数量 */
          quantity: null,
          /** 单位 */
          unit: ""
        }
      ]
    };

    addDialog({
      title: "新增订单信息",
      props: {
        formInline
      },
      width: "80%",
      closeOnClickModal: false,
      draggable: true,
      contentRenderer: () => h(CreateForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        // 通过子表单组件暴露的 getRef 获取真实的 ElForm 引用
        const FormRef = formRef.value.getRef();
        FormRef.validate(valid => {
          if (valid) {
            // 获取表单数据
            const curData = options.props.formInline as FormItemProps;
            // 格式化商品列表的价格和数量为数字
            if (curData.productList && Array.isArray(curData.productList)) {
              curData.productList = curData.productList.map(item => ({
                ...item,
                price: parseFloat(item.price) || 0,
                quantity: parseInt(item.quantity) || 0
              }));
            }

            createOrder(curData)
              .then(res => {
                if (res.status.code === 200) {
                  message("订单信息已保存", { type: "success" });
                  done(); // 关闭弹框
                  getStatusList(); // 刷新列表
                }
              })
              .catch(err => {
                message("订单信息保存失败", { type: "error" });
              });
          }
        });
      }
    });
  };

  /**
   * 打开文件上传弹窗
   */
  const uploadExcleDialog = () => {
    addDialog({
      title: "导入Excle",
      width: "600px",
      closeOnClickModal: false,
      draggable: true,
      contentRenderer: () => h(UploadForm, { ref: uploadRef }),
      beforeSure: (done, { options }) => {
        // 获取上传的文件列表
        const files = uploadRef.value.getFiles();
        console.log("上传的文件:", files);

        if (files.length === 0) {
          message("请选择要上传的文件", { type: "warning" });
          return;
        }

        // 这里可以添加实际的文件上传处理逻辑
        // 例如：调用上传API处理文件
        message("文件上传成功", { type: "success" });
        done(); // 关闭弹框
        uploadRef.value.clearFiles(); // 清空文件列表
      }
    });
  };

  return {
    addOrderDialog,
    uploadExcleDialog
  };
}

/** 导出Excle功能 */
const exportExcle = async () => {
  try {
    // 判断时间是否为空
    let startTime = 0,
      endTime = 0;
    if (searchState.value.timeRange == null) {
      startTime = 0;
      endTime = 0;
    } else {
      startTime = Math.floor(searchState.value.timeRange[0] / 1000);
      endTime = Math.floor(searchState.value.timeRange[1] / 1000);
    }

    const blob = await downloadExcel({
      typeid: searchState.value.status,
      orderno: searchState.value.orderNo,
      purchasingunit: searchState.value.purchasingUnit,
      contactsname: searchState.value.purchaser,
      starttime: startTime,
      endtime: endTime
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `订单导出_${new Date()
      .toLocaleDateString()
      .replace(/\//g, "-")}.xlsx`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error("导出失败", error);
  }
};

export {
  searchColumns,
  searchState,
  columns,
  childColumns,
  filterStatus,
  statusFilterList,
  pagination,
  productList,
  expandedRowKeys,
  handleRowClick,
  handleSelect,
  handlerSearch,
  getStatusList,
  handlePageChange,
  handleSizeChange,
  handleExpandChange,
  changeOrderStatus,
  changeOrderStatusClose,
  changeOrderStatusProblem,
  exportExcle
};
